﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace Utilities
{
    public class DxTimer
    {
        static DxTimer msDefaultInstance;
        static public DxTimer Singleton
        {
            get
            {
                if (msDefaultInstance == null)
                    msDefaultInstance = new DxTimer();

                return msDefaultInstance;
            }
        }

        //CPU頻率, 我們假定他永遠不變
        long mFrequency = 0;
        long mCurrentClock = 0;
        string mTimerName;


        //他是有專屬timer需求的，不能不放出來
        private DxTimer()
        {
            mTimerName = "Default Timer";
            QueryPerformanceFrequency(ref mFrequency);
        }

        public DxTimer(string timerName)
        {
            mTimerName = timerName;
            QueryPerformanceFrequency(ref mFrequency);
        }

        public void Reset()
        {
            QueryPerformanceCounter(ref mCurrentClock);
        }


        public double ElaspedTime()
        {
            return ElaspedTime(false);
        }

        public double ElaspedTime(bool ResetTimer)
        {
            long nowClock = 0;
            QueryPerformanceCounter(ref nowClock);
            double ret = (double)(nowClock - mCurrentClock) / mFrequency;

            if (ResetTimer)
                Reset();

            return ret;
        }



        //取得目前CPU頻率(每秒)
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32")]
        private static extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);

        //取得目前CPU運行clock數
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("Kernel32")]
        private static extern bool QueryPerformanceCounter(ref long PerformanceCount);
    }
}
